<?php
namespace app\api\controller;

use app\common\controller\ApiController;
use think\App;
use \app\admin\traits\Curd;
use think\facade\Db;
use app\api\controller\Adv;
use app\api\model\Token;
use app\api\model\User as ModelUser;
use PhpOffice\PhpSpreadsheet\Reader\Xls\MD5;

class Shop extends ApiController
{
    protected $noNeedLogin = [
        "get_banner_list",
        "get_classification_list",
        "recommend_service",
        "test",
        "get_navigation_list",
        "select_technician",
        "technician_detail",
        "gettime_period",
        "get_proitime"
        
    ];
    protected $mustLogin = [];
    protected $counter = 0;

    use \app\admin\traits\Curd;
    public function __construct(App $app)
    {
        parent::__construct($app);
    }
    //轮播图列表
    public function get_banner_list()
    {
        $param = $this->request->param();
        $num = isset($param['num'])?$param['num']:5;
        $list = Db::name("banner")->order('id desc')->paginate($num);
        $this->success('获取成功', $list);
    }

  
    //导航列表
    public function get_navigation_list(){
        $list = Db::name("classification")->order('id desc')->paginate(10);
        $list = $list->toArray();
        $this->success('获取成功', $list);
    }

    //推荐服务
    public function recommend_service(){
        $list = Db::name("service_goods")->where("is_recommend",1)
            ->order('create_time desc')
            ->field("id,title,zhu_img,price,duration,is_recommend,salesroom_id")
            ->paginate(10)->each(function($item){
                $admin = Db::name("system_admin")->where("id",$item["salesroom_id"])->find();
                if(!empty($admin)){
                    $item["salesroom_name"] = $admin["salesroom_name"];
                }else{
                    $item["salesroom_name"] = "";
                }
                return $item;
            });
        $list = $list->toArray();
        $this->success('获取成功', $list);
    }

    //选择技师列表
    public function select_technician(){
        $param = $this->request->param();
        if(empty($param["project_id"])){
            $this->error('参数传递错误!');
        }
        if(empty($param["salesroom_id"])){
            $this->error('参数传递错误!');
        }
        $where = [];
        if(!empty($param['project_id']) && isset($param['project_id']))
        {
            $where[] = [
                ['service_goods_id', 'like', '%'.$param['project_id'].','.'%']
            ];
        }
        if(!empty($param['salesroom_id']) && isset($param['salesroom_id']))
        {
            $where[] = [
                ['salesroom_id', '=', $param['salesroom_id']]
            ];
        }
       
        $service_goods = Db::name("service_technician")->where($where)
                ->paginate()->each(function($item){
                    $service_goods_id = explode(",",$item["service_goods_id"]);
                    $service_goods_id = array_filter($service_goods_id);
                    foreach($service_goods_id as $k=>$v){
                        $service_goodname[] = Db::name("service_goods")->where("id",$v)->value("title");
                    }
                    $service_goodname = implode(" ",$service_goodname);
                    $item["service_goodname"] = $service_goodname;
                    return $item;
                });
          
        $this->success('获取成功', $service_goods);
    }

    //技师详情
    public function technician_detail(){
        $param = $this->request->param();
        if (empty($param['tid'])) {
            $this->error('参数传递错误!');
        }
        if (empty($param['longitude'])) {
            $this->error('参数传递错误!');
        }
        if (empty($param['latitude'])) {
            $this->error('参数传递错误!');
        }
        $list = Db::name("service_technician")->where("id",$param["tid"])->field("id,service_name,service_img,brief_introduction,score,sales_volume,salesroom_id,service_goods_id")->find();
        $dianp = Db::name("system_admin")->where("id",$list["salesroom_id"])->field("id,salesroom_name,business_hours,longitude,latitude,address,salesroom_phone")->find();
        $dujl = $this->distance($param['longitude'], $param['latitude'], $dianp["longitude"], $dianp["latitude"], "K");
        $dujl = substr($dujl,0,4);
       
        //查询所有店铺经纬度
        $system_admin = Db::name("system_admin")->where("type",2)->where("status",1)->select()->toArray();
        $asd = [];
        foreach($system_admin as $k=>$v){
            $distance = $this->distance($param['longitude'], $param['latitude'], $v["longitude"], $v["latitude"], "K"); // 以公里为单位
            $distance = substr($distance,0,4);
            $xin = [
                "id"=>$v["id"],
                "juli"=>$distance
            ];
            $asd[] = $xin;
        }
        $values = array_column($asd, 'juli');
 
        // 使用min函数找出最小值
        $minValue = min($values);
        //判断是否是最近距离
        if($dujl <= $minValue){
            $dianp["is_itnearby"] = true;
        }else{
            $dianp["is_itnearby"] = false;
        }

        //技师绑定项目
        $service_goods_id = explode(",",$list["service_goods_id"]);
        $service_goods_id = array_filter($service_goods_id);
        $service_goodarr = [];
        foreach($service_goods_id as $ke=>$va){
            $service_goods = Db::name("service_goods")->where("id",$va)->field("id,title,price,duration")->find();
            $duration = bcmul($service_goods["duration"],60);
            $stop_time= date("H:i",time());
            //十分钟之后 600秒
            $ten=date("H:i",strtotime($stop_time)+$duration);
            $halfHours = $this->splitTimeIntoHalfHours($stop_time, $ten);
            $service_goods["halfHours"] = $halfHours;
            array_push($service_goodarr,$service_goods);
        }
 
        $list["merchant"] = $dianp;
        $list["service_goodarr"] = $service_goodarr;
        $this->success('获取成功', $list);
    }

    //分割时间段
    function splitTimeIntoHalfHours($startTime, $endTime) {
        $startTime = strtotime($startTime);
        $endTime = strtotime($endTime);
        $halfHours = array();
     
        while ($startTime <= $endTime) {
            $halfHours[] = date("H:i", $startTime);
            $startTime = strtotime('+10 minutes', $startTime);
        }
        return $halfHours;
    }

    //获取技师预约时间段
    public function gettime_period(){
        $param = $this->request->param();
        // if (empty($param['appointment_date'])) {
        //     $this->error('预约日期不能为空!');
        // }
        if (empty($param['service_technician_id'])) {
            $this->error('技师id不能为空!');
        }
        //根据技师id查询店铺营业时间 salesroom_id
        $service_technician = Db::name("service_technician")->where("id",$param["service_technician_id"])->find();

        $system_admin = Db::name("system_admin")->where("id",$service_technician["salesroom_id"])->find();
        $business_hours = explode("-",$system_admin["business_hours"]);

        //十分钟之后 600秒
        $ten=date("H:i",strtotime($business_hours[1]));
        $halfHours = $this->splitTimeIntoHalfHours($business_hours[0], $ten);

        $this->success('获取成功', $halfHours);
    }
 
    function distance($lat1, $lon1, $lat2, $lon2, $unit) {
        $theta = $lon1 - $lon2;
        $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
        $dist = acos($dist);
        $dist = rad2deg($dist);
        $miles = $dist * 60 * 1.1515;
        $unit = strtoupper($unit);
     
        if ($unit == "K") {
            return ($miles * 1.609344);
        } else if ($unit == "N") {
            return ($miles * 0.8684);
        } else {
            return $miles;
        }
    }
     
    // // 使用示例
    // $distance = distance(32.9697, -96.8032, 29.46786, -98.53506, "M"); // 以英里为单位
    // echo $distance . " Miles\n";
     
    // $distance = distance(32.9697, -96.8032, 29.46786, -98.53506, "K"); // 以公里为单位
    // echo $distance . " Kilometers\n";
     
    // $distance = distance(32.9697, -96.8032, 29.46786, -98.53506, "N"); // 以海里为单位
    // echo $distance . " Nautical Miles\n";


    //获取项目下单时间
    public function get_proitime(){
        $param = $this->request->param();
        if (empty($param['service_goods_id'])) {
            $this->error('项目id不能为空!');
        }
        if (empty($param['service_technician_id'])) {
            $this->error('技师id不能为空!');
        }
        if (empty($param['reservation_data'])) {
            $this->error('预约日期不能为空!');
        }
        $list = Db::name("order_item")->alias("oi")
        ->join("order o","oi.oid=o.id")
        ->where("o.status",'in',[2,3,7])
        ->where("oi.service_goods_id",$param["service_goods_id"])
        ->where("oi.service_technician_id",$param["service_technician_id"])
        ->where("oi.reservation_data",$param["reservation_data"])
        ->field("oi.id,oi.oid,oi.service_technician_id,oi.service_goods_id,oi.reservation_data,oi.reservation_time,oi.append_time,oi.appstart_time")
        ->select();
        $this->success('获取成功', $list);
    }








    //下单加入购物车
    public function teacorder_cart(){
        $param = $this->request->param();
        if (empty($param['service_goods'])) {
            $this->error('项目id不能为空!');
        }
        if (empty($param['service_technician_id'])) {
            $this->error('技师id不能为空!');
        }
        if (empty($param['appointment_date'])) {
            $this->error('预约日期不能为空!');
        }
        if (empty($param['appointment_time'])) {
            $this->error('预约时间不能为空!');
        }
        if (empty($param['append_time'])) {
            $this->error('预约时间开始不能为空!');
        }
        if (empty($param['appstart_time'])) {
            $this->error('预约时间结束不能为空!');
        }
        

        $data = [
            "uid"=>$this->uid,
            "service_technician_id"=>$param["service_technician_id"],
            "service_goods"=>$param["service_goods"],
            "appointment_date"=>$param["appointment_date"],
            "appointment_time"=>$param["appointment_time"],
            "append_time"=>$param["append_time"],
            "appstart_time"=>$param["appstart_time"],
            "create_time"=>time(),
        ];

        Db::name("order_cart")->insert($data);
        $this->success('操作成功');
    }

    //购物车列表
    public function teacorder_cart_list(){
        $param = $this->request->param();
        if (empty($param['service_technician_id'])) {
            $this->error('技师id不能为空!');
        }
        $list = Db::name("order_cart")->where("uid",$this->uid)->where("service_technician_id",$param["service_technician_id"])->select();
        foreach($list as $k=>$v){
            $v["service_goods"] = Db::name("service_goods")->where("id",$v["service_goods"])->field("id,title,price,duration")->find();
            $v["service_technician"] = Db::name("service_technician")->where("id",$param["service_technician_id"])->field("id,service_name,service_img,score")->find(); 
            $list[$k] = $v;
        }
        $list["cart_num"] = count($list);
        //dump($list);die;
        $this->success('获取成功',$list);

    }

    //购物车删除
    public function teacorder_cart_del(){
        $param = $this->request->param();
        if (empty($param['cart_id'])) {
            $this->error('购物车id不能为空!');
        }
        $flag = Db::name("order_cart")->where("id",$param["cart_id"])->find();
        if(empty($flag)){
            $this->error('参数传递错误!');
        }
        Db::name("order_cart")->where("id",$param["cart_id"])->delete();
        $this->success('操作成功');
    }

    //判断是否加入购物车
    public function is_cart(){
        $param = $this->request->param();
        if (empty($param['service_technician_id'])) {
            $this->error('技师id不能为空!');
        }
        if (empty($param['service_goods'])) {
            $this->error('项目id不能为空!');
        }
        if (empty($param['appointment_date'])) {
            $this->error('预约日期不能为空!');
        }

        $flag = Db::name("order_cart")
        ->where("uid",$this->uid)
        ->where("appointment_date",$param["appointment_date"])
        ->where("service_technician_id",$param["service_technician_id"])
        ->where("service_goods",$param["service_goods"])
        ->find();
        if(!empty($flag)){
            $this->success('已加入购物车',$flag);
        }else{
            $this->error('未加入购物车!');
        }
    }

    //地区所有技师列表
    public function regional_technician(){
        $param = $this->request->param();
        if (empty($param['city'])) {
            $this->error('地区不能为空!');
        }
        $list = Db::name("service_technician")->where("city",$param["city"])->select();
        $this->success('获取成功',$list);
    }

 




 
    






    

    //服务产品搜索
    public function serive_good_resah(){
        $param = $this->request->param();
        if (empty($param['title'])) {
            $this->error('参数传递错误!');
        }
        $where = [];
        if(!empty($param['title']) && isset($param['title']))
        {
            $where = [
                ['title', 'like', '%'.$param['title'].'%']
            ];
        }
        $list = Db::name("service_goods")->where($where)
        ->order('create_time desc')
        ->field("id,title,zhu_img,server_label")
        ->paginate(10)->each(function($item){
            $service_duration = Db::name("service_duration")->where("service_gid",$item["id"])->order("id asc")->find();
            if(!empty($service_duration)){
                $item["spec_price"] = $service_duration["price"];
            }else{
                $item["spec_price"] = "";
            }
            //好评率
            $zong_num = Db::name("order_evaluate")->where("service_good_id",$item["id"])->count();
            $order_evaluate = Db::name("order_evaluate")->where("service_good_id",$item["id"])->where("star_rating","in","4,5")->count();
            if($zong_num == 0 || $order_evaluate== 0){
                $item["plsz"] =0;
            }else{
                $plsz = bcdiv($order_evaluate,$zong_num,2);
                $plsz = intval($plsz * 100);
                $item["plsz"] =$plsz;
            }
            //已售 
            $sold = Db::name("order")->where("service_gid",$item["id"])->where("status",7)->count();
            $item["sold"] =$sold;
            $item["server_label"] = explode(",",$item["server_label"]);
            return $item;
        });
        $list = $list->toArray();
        $this->success('获取成功', $list);
    } 

  

    //我的地址列表
    public function myaddress_list(){
        $list = Db::name("address")->where("uid",$this->uid)->order('create_time desc')
            ->paginate(10);
        $this->success('获取成功', $list);
    }

    //地址设置默认
    public function address_set_defalut(){
        $param = $this->request->param();
        if(empty($param['address_id'])){
            $this->error('未找到指定参数');
        }
        Db::name("address")->where("uid",$this->uid)->update(["is_default"=>0]);
        Db::name("address")->where("uid",$this->uid)->where("id",$param['address_id'])->update(["is_default"=>1]);
        $this->success('设置成功');
    }

    //添加地址
    public function add_address(){
        $param = $this->request->param();
        if(empty($param['username'])){
            $this->error('姓名不能为空');
        }
        if(empty($param['phone'])){
            $this->error('手机号不能为空');
        }
        if(empty($param['address_pca'])){
            $this->error('省市区地址不能为空');
        }
        if(empty($param['address_detailed'])){
            $this->error('详细地址不能为空');
        }
        $param["uid"] = $this->uid;
        $param["create_time"] = time();
        Db::name("address")->insert($param);
        $this->success('添加成功');
    }

    //编辑地址显示
    public function address_look(){
        $param = $this->request->param();
        if(empty($param['address_id'])){
            $this->error('未找到指定参数');
        }
        $list = Db::name("address")->where("id",$param['address_id'])->find();
        $this->success('获取成功', $list);
    }

    //编辑地址
    public function edit_address()
    {
        $param = $this->request->param();
        if(empty($param['address_id'])){
            $this->error('未找到指定参数');
        }
        if(empty($param['username'])){
            $this->error('姓名不能为空');
        }
        if(empty($param['phone'])){
            $this->error('手机号不能为空');
        }
        if(empty($param['address_pca'])){
            $this->error('省市区地址不能为空');
        }
        if(empty($param['address_detailed'])){
            $this->error('详细地址不能为空');
        }
        $address_id = $param["address_id"];
        unset($param["address_id"]);
        Db::name("address")->where("id",$address_id)->update($param);
        $this->success('修改成功');
    }

    //删除地址
    public function del_address(){
        $param = $this->request->param();
        if(empty($param['address_id'])){
            $this->error('未找到指定参数');
        }
        Db::name("address")->where("id",$param['address_id'])->delete();
        $this->success('删除成功');
    }

    //我的默认地址
    public function mu_defa_address(){
        $list = Db::name("address")->where("uid",$this->uid)->where("is_default",1)->find();
        $this->success('获取成功', $list);
    }




    //个人数据
    public function personal_data(){
        $cou_num = Db::name("coupon_user")->where("uid",$this->uid)->where("status",1)->count();
        $colle_num = Db::name("my_collection")->where("uid",$this->uid)->count();
        $list = [
            "coupon_num"=>$cou_num,
            "collection_num"=>$colle_num
        ];
        $this->success('获取成功', $list);
    }

    //技师基础资料修改
    public function technician_data_modification(){
        $param = $this->request->param();
        if(empty($param['st_id'])){
            $this->error('未找到指定技师');
        }
        $st_id = $param["st_id"];
        unset($param["st_id"]);
        Db::name("service_technician")->where("id",$st_id)->update($param);
        $this->success('修改成功');
    }

     //上传图片
     public function upload()
     {
         $file = request()->file('file');
         if (empty($file)) {
             $this->error('请选择上传文件');
         }
         try {
             validate('app\api\validate\Upload')
                 ->scene('img')
                 ->check(['file' => $file]);
             $savename = \think\facade\Filesystem::disk('public')->putFile('uploads', $file);
             $url = request()->domain() . '/' . $savename;
             $this->success('上传成功',$url);
         } catch (\think\exception\ValidateException $e) {
             $this->error('上传失败',$e->getMessage());
         }
     }
     
     //技师修改密码
     public function tec_editpwd(){
        $param = $this->request->param();
        if(empty($param['st_id'])){
            $this->error('技师id不能为空');
        }
        if(empty($param['password'])){
            $this->error('新密码不能为空');
        }
        if(empty($param['new_password'])){
            $this->error('密码不能为空');
        }
        if($param['password'] != $param['new_password']){
            $this->error('两次密码不一致');
        }
        Db::name("service_technician")->where("id",$param['st_id'])->update(["password"=>md5($param['password'])]);
        $this->success('修改成功');
     }

     //修改用户信息
     public function modify_user_information(){
        $param = $this->request->param();
        if(empty($param['nickname'])){
            $this->error('昵称不能为空');
        }
        if(empty($param['avatar'])){
            $this->error('头像不能为空');
        }
        if(empty($param['gender'])){
            $this->error('性别不能为空');
        }
        Db::name("user")->where("id",$this->uid)->update($param);
        $this->success('修改成功');
     }

     //配置数据
     public function config_data(){
        $param = $this->request->param();
        if(empty($param['type'])){
            $this->error('类型不能为空');
        }
        if($param["type"] == 1){
            $service_agreement = sysconfig('contact','service_agreement');
            $service_agreement = html_entity_decode($service_agreement);
            $data = str_replace(array("\r", "\n\n", "\s", "\t", "\n"), '<br/>', $service_agreement);
        }elseif($param["type"] == 2){
            $data = sysconfig('site','contact_phone');
        }else{
            $this->error('类型不存在');
        }
        $this->success('获取成功', $data);
     }

 
     //判断是否是服务技师
     public function is_service_technician(){
        $flag = Db::name("service_technician")->where("uid",$this->uid)->find();
        if(empty($flag)){
            $this->error('不是');
        }else{
            $this->success('是',$flag);
        }
        
     }

     //服务技师申请
     public function technician_application(){
        $param = $this->request->param();
        if(empty($param['username'])){
            $this->error('姓名不能为空');
        }
        if(empty($param['img'])){
            $this->error('头像不能为空');
        }
        if(empty($param['age'])){
            $this->error('年龄不能为空');
        }
        if(empty($param['phone'])){
            $this->error('手机号不能为空');
        }
        if(empty($param['sex'])){
            $this->error('性别不能为空');
        }
        $lfag = Db::name("technician_review")->where("status",0)->where("uid",$this->uid)->find();
        if(!empty($lfag)){
            $this->error('已申请,请勿重复申请');
        }
        $flag = Db::name("technician_review")->where("status",2)->where("uid",$this->uid)->find();
        if(!empty($flag)){
            Db::name("technician_review")->where("status",2)->where("uid",$this->uid)->update(["type"=>1]);
        }
        $param["uid"] = $this->uid;
        $param["create_time"] = time();
        Db::name("technician_review")->insert($param);
        $this->success('提交成功');
     }

     //技师审核状态
     public function technician_audit_status(){
        $list = Db::name("technician_review")->where("uid",$this->uid)->where("type",0)->find();
        $this->success('获取成功',$list);
     }



    // //H5用户登录
    // public function h5user_login()
    // {
    //     $param = $this->request->param();
    //     if (empty($param['username'])) {
    //         $this->error("登陆失败,账号不能为空");
    //     }
    //     if (empty($param['password'])) {
    //         $this->error("登陆失败,密码不能为空");
    //     }

    //     $flag = Db::name("h5manag_account")->where("username",$param["username"])->find();
    //     if(empty($flag)){
    //         $this->error("登陆失败,账户不存在");
    //     }
    //     if($flag["status"] == 1){
    //         $this->error("登陆失败,账户已锁定");
    //     }
    //     if($flag["password"] != md5($param["password"])){
    //         $this->error("登陆失败,密码错误");
    //     }
    //     $token = Auth::makeToken();
    //     $userToken = new Token();
    //     $userToken->setToken($token, $flag["id"], $this->method);
    //     $this->success('登录成功', ['token' => $token, 'method' => $this->method, 'h5user_id' => $flag["id"], 'h5userArr' => $flag]);
    // }

     

    
 
   
}
